package com.ruicar.afs.cloud.channel.channelworkflow.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.bizcommon.voucher.service.VoucherFlowService;
import com.ruicar.afs.cloud.channel.channelworkflow.condition.ChannelOnlineWorkFlowCondition;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskAssign;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskCreated;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskApproveRecordService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskAssignService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskCreatedService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.channelworkflow.vo.ChannelOnlineWorkTaskVo;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.mq.sender.ChannelIdToCommissionSystemSender;
import com.ruicar.afs.cloud.channel.common.mq.sender.ChannelOnlineInfoToCaseSender;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToArchive;
import com.ruicar.afs.cloud.channel.common.mq.sender.config.ArchiveConfig;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToArchiveImpl;
import com.ruicar.afs.cloud.channel.online.condition.ChannelAuthRegionCondition;
import com.ruicar.afs.cloud.channel.online.condition.ChannelBasicTempCondition;
import com.ruicar.afs.cloud.channel.online.entity.*;
import com.ruicar.afs.cloud.channel.online.service.*;
import com.ruicar.afs.cloud.channel.online.vo.ChannelOnlineInterFaceVo;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.constant.VoucherBuriedPointNo;
import com.ruicar.afs.cloud.common.modules.dto.mq.affiliation.AffiliationStatusInfo;
import com.ruicar.afs.cloud.common.modules.dto.mq.voucher.VoucherFlowInfoDto;
import com.ruicar.afs.cloud.common.modules.enums.BusinessType;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.QueryFLowCmdRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.TaskSubmitRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowCmdBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.*;

/**
 * @ClassName:ChannelOnlineController
 * @Description: 渠道上线审批-controller
 * @Author:mingzhi.li
 * @Date:2020/7/17 19:06
 * @Version: V1.0
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/channelOnlineWorkFlow")
@Api(value = "channelOnlineWorkFlow", description = "渠道上线申请审批")
public class ChannelOnlineWorkFlowController {
    private final WorkflowService workflowService;
    private final WorkTaskAssignService workTaskAssignService;
    private final WorkTaskCreatedService workTaskCreatedService;
    private final ChannelOnlineService channelOnlineService;
    private final WorkTaskDetailService workTaskDetailService;
    private final ChannelAccountInfoService channelAccountInfoService;
    private final ChannelRiskInfoService channelRiskInfoService;
    private final ChannelQuotaInfoService channelQuotaInfoService;
    private final ChannelAuthorizeRegionService channelAuthorizeRegionService;
    private final TsysAddressParamService service;
    private final ChannelAuthorizeVehicleTempService channelAuthorizeVehicleTempService;
    private final WorkTaskApproveRecordService workTaskApproveRecordService;
    private final ChannelArchivesInfoService channelArchivesInfoService;
    private UidGenerator uidGenerator;
    private final ChannelIdToCommissionSystemSender channelIdToCommissionSystemSender;
    private final SenderChannelToArchiveImpl senderChannelToArchiveImpl;
    private final ChannelOnlineInfoToCaseSender channelOnlineInfoToCaseSender;

    @PostMapping(value = "/getByCondition")
    @ApiOperation(value = "多条件分页渠道信息列表")
    public IResponse<IPage<ChannelBaseInfoTemp>> getByCondition(@RequestBody ChannelOnlineWorkFlowCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        //获取当前用户角色
        //condition.setUsername(SecurityUtils.getUsername());
        condition.setUserRoles(SecurityUtils.getRoles());
        IPage<List<ChannelOnlineWorkTaskVo>> channelList = workTaskAssignService.getChannelWorkFlowInfo(page, condition);
        return IResponse.success(channelList);
    }

    @RequestMapping(value = "/approveChannelWorkFlow", method = RequestMethod.POST)
    @ApiOperation(value = "提交上线流程")
    @SysLog("提交上线流程")
    @Transactional(rollbackFor = Exception.class)
    public IResponse approveChannelWorkFlow(@RequestBody ChannelOnlineWorkFlowCondition condition) throws JsonProcessingException {

        WorkTaskAssign assgin = workTaskAssignService.getOne(Wrappers.<WorkTaskAssign>query().lambda()
                .eq(WorkTaskAssign::getBizDataId, condition.getBizDataId()));

        WorkTaskCreated created = workTaskCreatedService.getOne(Wrappers.<WorkTaskCreated>query().lambda().eq(WorkTaskCreated::getBizDataId, condition.getBizDataId()));
        WorkTaskDetail detail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBizDataId, condition.getBizDataId()));
        //提交完成之后删除其他人员代办
        List<WorkTaskAssign> assignList = workTaskAssignService.list(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, condition.getBizDataId()));
        ChannelBaseInfoTemp infoTemp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda().eq(ChannelBaseInfoTemp::getId, condition.getChannelId()));
        ChannelRiskInfoTemp riskInfoTemp = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                .eq(ChannelRiskInfoTemp::getChannelId, detail.getBusinessKey()).eq(ChannelRiskInfoTemp::getBusinessType,detail.getBusinessType()));

        TaskSubmitRequest taskSubmitRequest = new TaskSubmitRequest();
        taskSubmitRequest.setGwtUserId(assgin.getAssignId());
        taskSubmitRequest.setAfsFlowKey(created.getAfsFlowKey());
        taskSubmitRequest.setBizDataId(created.getBizDataId());
        QueryFLowCmdRequest request = new QueryFLowCmdRequest();
        request.setFlowInstanceId(created.getFlowInstanceId());
        WorkFlowResponse<List<FlowCmdBean>> cmdResponse = workflowService.queryFlowCmd(request);
        List<FlowCmdBean> cmdList = cmdResponse.getAfsData();
        FlowCmdBean cmd = workTaskCreatedService.channelApprove(condition.getApprove(), cmdList);

        if(riskInfoTemp !=null){
            log.info("==================================修改应缴、实缴保证金==================================》");
            riskInfoTemp.setChannelDepositPaidIn(condition.getChannelDepositPaidIn());
            channelRiskInfoService.updateById(riskInfoTemp);
        }
        if (cmd != null) {
            log.info("==================================提交工作流开始==================================》");
            taskSubmitRequest.setCmdId(cmd.getId());
            ObjectMapper mapper = new ObjectMapper();
            //获取配置节点信息
            String json = mapper.writeValueAsString(infoTemp);
            JSONObject cancelJson = JSONObject.parseObject(json);
            if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())) {
                //新车业务类型
                cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.BUSINESS_TYPE), BUSINESS_TYPE_NEW_CAR);
            } else if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())) {
                //二手车业务类型
                cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.BUSINESS_TYPE), BUSINESS_TYPE_OLD_CAR);
            }
            workflowService.taskSubmit(taskSubmitRequest, cancelJson);
            condition.setBusinessKey(condition.getChannelId());
            condition.setBusinessType(detail.getBusinessType());
            condition.setTaskName(assgin.getTaskName());
            workTaskApproveRecordService.approveSave(condition, cmd);
            log.info("==================================业务逻辑处理开始==================================》");
            String taskMemo = created.getTaskMemo();
            if (!StrUtil.isBlank(taskMemo)) {
                JSONObject jsonMemo = (JSONObject) JSONObject.parse(taskMemo);
                String memo = (String) jsonMemo.get(AfsEnumUtil.key(ChannelAfsFlowEnum.NODE_LABEL));
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_BACK).equals(cmd.getCmdDis())) {
                    //首节点
                    if (FIRST_NODE.equals(memo)) {
                        //首节点(退回特殊处理逻辑)：退回
                        if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())) {
                            infoTemp.setChannelStatus(VALUE_CHANNEL_STATUS_THREE);
                        }
                        if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())) {
                            infoTemp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_THREE);
                        }
                        infoTemp.setEventId(uidGenerator.getUID());
                        workTaskDetailService.removeById(detail);
                        workTaskCreatedService.removeById(created);
                    }
                }
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_REFUSE).equals(cmd.getCmdDis())) {
                    //首节点(退回特殊处理逻辑)//拒绝
                    if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())) {
                        infoTemp.setChannelStatus(VALUE_CHANNEL_STATUS_FOUR);
                    }
                    if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())) {
                        infoTemp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_FOUR);
                    }
                }
                if (AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_SUBMIT).equals(cmd.getCmdDis()) && END_NODE.equals(memo)) {
                    infoTemp.setEventId(uidGenerator.getUID());
                    if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())) {
                        infoTemp.setChannelStatus(VALUE_CHANNEL_STATUS_ZERO);
                    }
                    if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())) {
                        infoTemp.setChannelStatusOldCar(VALUE_CHANNEL_STATUS_ZERO);
                    }
                    //Step 2：同步信息到案件服务
                    List<TsysAddressParam> paramList = service.list(Wrappers.<TsysAddressParam>query().lambda().orderByAsc(TsysAddressParam::getValue));
                    ChannelOnlineInterFaceVo vo = new ChannelOnlineInterFaceVo();
                    vo.setChannelBaseInfo(infoTemp);
                    //新车
                    if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())) {
                        //查询新车风控信息
                        List<ChannelRiskInfoTemp> channelRiskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
                        List<ChannelRiskInfoTemp> riskInfoTempList = new ArrayList<>();
                        if (channelRiskInfoTempList != null && channelRiskInfoTempList.size() > 0) {
                            channelRiskInfoTempList.forEach(risk -> {
                                risk.setId(null);
                                riskInfoTempList.add(risk);
                            });
                            //返回新车风控数据
                            vo.setRisk(riskInfoTempList);
                        }

                        //查询新车渠道保证金信息
                        List<ChannelQuotaInfoTemp> channelQuotaInfoTempList = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                                .eq(ChannelQuotaInfoTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
                        List<ChannelQuotaInfoTemp> quotaInfoTempList = new ArrayList<>();
                        if (channelQuotaInfoTempList != null && channelQuotaInfoTempList.size() > 0) {
                            channelQuotaInfoTempList.forEach(quota -> {
                                quota.setId(null);
                                quotaInfoTempList.add(quota);
                            });
                            //返回新车渠道保证金信息
                            vo.setQuota(quotaInfoTempList);
                        }

                        //查询新车渠道授权区域信息
                        List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                                .eq(ChannelAuthorizeRegionTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
                        List<ChannelAuthorizeRegionTemp> authorizeRegionTempList = new ArrayList<>();
                        if (channelAuthorizeRegionTempList != null && channelAuthorizeRegionTempList.size() > 0) {
                            channelAuthorizeRegionTempList.forEach(authorize -> {
                                authorize.setId(null);
                                authorizeRegionTempList.add(authorize);
                            });
                            //返回新车授权区域信息
                            vo.setRegion(authorizeRegionTempList);
                        }

                        //查询新车收款账号信息
                        List<ChannelReceivablesAccountTemp> accountList = new ArrayList<>();
                        List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                                .eq(ChannelReceivablesAccountTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_NEW_CAR));
                        if (accountTempList != null && accountTempList.size() > 0) {
                            //修改收款账号状态为启用
                            for (ChannelReceivablesAccountTemp accountTemp : accountTempList) {
                                accountTemp.setStatus(ACCOUNT_STATUS_ZERO);
                                channelAccountInfoService.updateById(accountTemp);
                                accountTemp.setId(null);
                                accountList.add(accountTemp);
                            }
                            //返回收款账号信息
                            vo.setAcount(accountList);
                        }

                        //查询新车授权车型
                        List<ChannelAuthorizeVehicleTemp> vehicleTempList = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                                .eq(ChannelAuthorizeVehicleTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
                        List<ChannelAuthorizeVehicleTemp> authorizeVehicleList = new ArrayList<>();
                        if (vehicleTempList != null && vehicleTempList.size() > 0) {
                            vehicleTempList.forEach(authorize -> {
                                authorize.setId(null);
                                authorizeVehicleList.add(authorize);
                            });
                            //返回授权车型
                            vo.setVehicle(vehicleTempList);
                        }
                        //赋值业务类型
                        vo.setBusinessType(detail.getBusinessType());
                        //同步开始(mq)
                        AfsTransEntity<ChannelOnlineInterFaceVo> transEntity = new AfsTransEntity<>();
                        transEntity.setTransCode(MqTransCode.CHANNEL_ONLINE_DEALER_INFO__TO_CASE);
                        transEntity.setData(vo);
                        channelOnlineInfoToCaseSender.sendForCaseChannelOnlineInfo(transEntity);
                        //channelOnlineService.synchronousDataToCase(vo);
                        //插入档案日志
                        channelArchivesInfoService.saveArchivesInfo(condition,detail.getBusinessType());

                    }
                    //二手车
                    if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())) {
                        //查询新车风控信息
                        List<ChannelRiskInfoTemp> channelRiskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
                        List<ChannelRiskInfoTemp> riskInfoTempList = new ArrayList<>();
                        if (channelRiskInfoTempList != null && channelRiskInfoTempList.size() > 0) {
                            channelRiskInfoTempList.forEach(risk -> {
                                risk.setId(null);
                                riskInfoTempList.add(risk);
                            });
                            //返回新车风控数据
                            vo.setRisk(riskInfoTempList);
                        }

                        //查询新车渠道保证金信息
                        List<ChannelQuotaInfoTemp> channelQuotaInfoTempList = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                                .eq(ChannelQuotaInfoTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelQuotaInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
                        List<ChannelQuotaInfoTemp> quotaInfoTempList = new ArrayList<>();
                        if (channelQuotaInfoTempList != null && channelQuotaInfoTempList.size() > 0) {
                            channelQuotaInfoTempList.forEach(quota -> {
                                quota.setId(null);
                                quotaInfoTempList.add(quota);
                            });
                            //返回新车渠道保证金信息
                            vo.setQuota(quotaInfoTempList);
                        }

                        //查询新车渠道授权区域信息
                        List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                                .eq(ChannelAuthorizeRegionTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelAuthorizeRegionTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
                        List<ChannelAuthorizeRegionTemp> authorizeRegionTempList = new ArrayList<>();
                        if (channelAuthorizeRegionTempList != null && channelAuthorizeRegionTempList.size() > 0) {
                            channelAuthorizeRegionTempList.forEach(authorize -> {
                                authorize.setId(null);
                                authorizeRegionTempList.add(authorize);
                            });
                            //返回新车授权区域信息
                            vo.setRegion(authorizeRegionTempList);
                        }

                        //查询新车收款账号信息
                        List<ChannelReceivablesAccountTemp> accountList = new ArrayList<>();
                        List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda()
                                .eq(ChannelReceivablesAccountTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelReceivablesAccountTemp::getAccountAttribute, BUSINESS_TYPE_OLD_CAR));
                        if (accountTempList != null && accountTempList.size() > 0) {
                            //修改收款账号状态为启用
                            for (ChannelReceivablesAccountTemp accountTemp : accountTempList) {
                                accountTemp.setStatus(ACCOUNT_STATUS_ZERO);
                                channelAccountInfoService.updateById(accountTemp);
                                accountTemp.setId(null);
                                accountList.add(accountTemp);
                            }
                            //返回收款账号信息
                            vo.setAcount(accountList);
                        }

                        //查询新车授权车型
                        List<ChannelAuthorizeVehicleTemp> vehicleTempList = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda()
                                .eq(ChannelAuthorizeVehicleTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelAuthorizeVehicleTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
                        List<ChannelAuthorizeVehicleTemp> authorizeVehicleList = new ArrayList<>();
                        if (vehicleTempList != null && vehicleTempList.size() > 0) {
                            vehicleTempList.forEach(authorize -> {
                                authorize.setId(null);
                                authorizeVehicleList.add(authorize);
                            });
                            //返回授权车型
                            vo.setVehicle(vehicleTempList);
                        }
                        //赋值业务类型
                        vo.setBusinessType(detail.getBusinessType());
                        //同步开始
                        AfsTransEntity<ChannelOnlineInterFaceVo> transEntity = new AfsTransEntity<>();
                        transEntity.setTransCode(MqTransCode.CHANNEL_ONLINE_DEALER_INFO__TO_CASE);
                        transEntity.setData(vo);
                        channelOnlineInfoToCaseSender.sendForCaseChannelOnlineInfo(transEntity);
                        //channelOnlineService.synchronousDataToCase(vo);
                        //插入档案日志
                        channelArchivesInfoService.saveArchivesInfo(condition,detail.getBusinessType());
                    }


                    //Step 3：优先同步授权区域信息(进件授权)
                    List<ChannelAuthorizeRegionTemp> regionTempList = new ArrayList<>();
                    if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType()) || VALUE_CHANNEL_STATUS_ZERO.equals(infoTemp.getChannelStatusOldCar())) {
                        ChannelRiskInfoTemp channelRiskNew = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));

                        if (channelRiskNew != null) {
                            if (TYPE_NO.equals(channelRiskNew.getAuthRegionSwitch())) {
                                for (int i = 0; i < paramList.size(); i++) {
                                    TsysAddressParam param = paramList.get(i);
                                    ChannelAuthorizeRegionTemp tegionTemp = new ChannelAuthorizeRegionTemp();
                                    tegionTemp.setCode(param.getValue());
                                    tegionTemp.setIsParent(param.getIsParent() + "");
                                    tegionTemp.setTitle(param.getLabel());
                                    tegionTemp.setChannelId(infoTemp.getId());
                                    tegionTemp.setParentId(param.getUpperCode());
                                    tegionTemp.setBusinessType(BUSINESS_NEW_CAR);
                                    regionTempList.add(tegionTemp);
                                }
                            }
                        }
                    }

                    if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType()) || VALUE_CHANNEL_STATUS_ZERO.equals(infoTemp.getChannelStatus())) {
                        ChannelRiskInfoTemp channelRiskOld = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                                .eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId())
                                .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
                        if (channelRiskOld != null) {
                            if (TYPE_NO.equals(channelRiskOld.getAuthRegionSwitch())) {
                                for (int i = 0; i < paramList.size(); i++) {
                                    TsysAddressParam param = paramList.get(i);
                                    ChannelAuthorizeRegionTemp tegionTemp = new ChannelAuthorizeRegionTemp();
                                    tegionTemp.setCode(param.getValue());
                                    tegionTemp.setIsParent(param.getIsParent() + "");
                                    tegionTemp.setTitle(param.getLabel());
                                    tegionTemp.setChannelId(infoTemp.getId());
                                    tegionTemp.setParentId(param.getUpperCode());
                                    tegionTemp.setBusinessType(BUSINESS_OLD_CAR);
                                    regionTempList.add(tegionTemp);
                                }
                            }
                        }
                    }

                    List<ChannelAuthorizeRegionTemp> channelAuthorizeRegionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda()
                            .eq(ChannelAuthorizeRegionTemp::getChannelId, infoTemp.getId()));
                    ChannelAuthRegionCondition channelAuthRegionCondition = new ChannelAuthRegionCondition();
                    if (channelAuthorizeRegionTempList != null && channelAuthorizeRegionTempList.size() > 0) {
                        channelAuthorizeRegionTempList.forEach(authorizeRegion -> {
                            if(VALUE_CHANNEL_STATUS_ZERO.equals(infoTemp.getChannelStatus()) && BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType()) ){
                                //如果新车已启用，且当前审批流程为二手车上线 ，传入所有授权区域
                                if (BUSINESS_TYPE_NEW_CAR.equals(authorizeRegion.getBusinessType())) {
                                    authorizeRegion.setBusinessType(BUSINESS_NEW_CAR);
                                } else if (BUSINESS_TYPE_OLD_CAR.equals(authorizeRegion.getBusinessType())) {
                                    authorizeRegion.setBusinessType(BUSINESS_OLD_CAR);
                                }
                                regionTempList.add(authorizeRegion);
                            }else if(VALUE_CHANNEL_STATUS_ZERO.equals(infoTemp.getChannelStatusOldCar()) && BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType()) ){
                                //如果二手车已启用，且当前审批流程为新车上线 ，传入所有授权区域
                                if (BUSINESS_TYPE_NEW_CAR.equals(authorizeRegion.getBusinessType())) {
                                    authorizeRegion.setBusinessType(BUSINESS_NEW_CAR);
                                } else if (BUSINESS_TYPE_OLD_CAR.equals(authorizeRegion.getBusinessType())) {
                                    authorizeRegion.setBusinessType(BUSINESS_OLD_CAR);
                                }
                                regionTempList.add(authorizeRegion);
                            }else if(BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())){
                                //单独传入新车
                                if (BUSINESS_TYPE_NEW_CAR.equals(authorizeRegion.getBusinessType())) {
                                    authorizeRegion.setBusinessType(BUSINESS_NEW_CAR);
                                    regionTempList.add(authorizeRegion);
                                }
                            }else if(BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())){
                                //单独传入二手车
                                if (BUSINESS_TYPE_OLD_CAR.equals(authorizeRegion.getBusinessType())) {
                                    authorizeRegion.setBusinessType(BUSINESS_OLD_CAR);
                                    regionTempList.add(authorizeRegion);
                                }
                            }
                        });
                    }
                    channelAuthRegionCondition.setRegions(regionTempList);
                    channelAuthRegionCondition.setType(AUTHORIZE_TYPE_ADD);
                    //同步授权区域到进件授权
                    channelOnlineService.synchronousAuthRegion(channelAuthRegionCondition);


                    //Step 4:创建账号
                    List<ChannelRiskInfoTemp> newRisk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId())
                            .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_NEW_CAR));
                    List<ChannelRiskInfoTemp> oldRisk = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, infoTemp.getId())
                            .eq(ChannelRiskInfoTemp::getBusinessType, BUSINESS_TYPE_OLD_CAR));
                    ChannelBasicTempCondition dto = new ChannelBasicTempCondition();
                    dto.setChannelId(infoTemp.getId());
                    dto.setChannelAdmin(infoTemp.getChannelAdmin());
                    dto.setChannelCode(infoTemp.getChannelCode());
                    dto.setChannelFullName(infoTemp.getChannelFullName());
                    dto.setChannelType(infoTemp.getChannelType());
                    dto.setHierarchy(infoTemp.getHierarchy());
                    dto.setIdentityNumber(infoTemp.getChannelAdminIdCard());
                    dto.setEmail(infoTemp.getChannelAdminMail());
                    dto.setPhone(infoTemp.getChannelAdminTel());
                    dto.setChannelBelong(infoTemp.getChannelBelong());
                    dto.setChoiceCardealerSwitch(infoTemp.getChoiceCardealerSwitch());
                    dto.setChoiceCardealerSwitchOld(infoTemp.getChoiceCardealerSwitchOld());
                    if (newRisk != null && newRisk.size() > 0) {
                        dto.setNewCarUserHierarchy(newRisk.get(0).getAccountMaxNum());
                    }
                    if (oldRisk != null && oldRisk.size() > 0) {
                        dto.setOldCarUserHierarchy(oldRisk.get(0).getAccountMaxNum());
                    }
                    channelOnlineService.createByParentId(dto);
                    //测试凭证 异常暂时捕捉
                    try{
                    //判断是否保证金且保证金金额不为零
                    if (vo.getRisk() != null && vo.getRisk().size() > 0 && vo.getRisk().get(0).getChannelDepositPaidIn()!=null&&vo.getRisk().get(0).getChannelDepositPaidIn().compareTo(BigDecimal.ZERO)!=0) {
                      VoucherFlowInfoDto voucherFlowInfoDto = new VoucherFlowInfoDto();
                        voucherFlowInfoDto.setTransNo(infoTemp.getEventId().toString());
                        voucherFlowInfoDto.setDealerName(infoTemp.getChannelFullName());
                        voucherFlowInfoDto.setBuriedPointNo(VoucherBuriedPointNo.depositCollection);
                        voucherFlowInfoDto.setKeepAccountDate(new Date());
                        // 业务类型
                        if (BUSINESS_TYPE_NEW_CAR.equals(detail.getBusinessType())) { //新车
                            voucherFlowInfoDto.setBusinessType(BusinessType.NEW_CAR);
                        } else if (BUSINESS_TYPE_OLD_CAR.equals(detail.getBusinessType())) {//新车
                            voucherFlowInfoDto.setBusinessType(BusinessType.OLD_CAR);
                        } else {
                            return IResponse.fail(MessageFormat.format("业务类型:{0},暂不支持！", detail.getBusinessType()));
                        }
                        IResponse iResponse = channelOnlineService.send(voucherFlowInfoDto);
                        if (!CommonConstants.SUCCESS.equals(iResponse.getCode())) {
                            log.error("渠道名称：{},凭证流水数据推送失败！", voucherFlowInfoDto.getDealerName());
                        }
                        Assert.isTrue(CommonConstants.SUCCESS.equals(iResponse.getCode()), "凭证流水数据推送失败！");
                    }
                    }catch (Exception e){
                        log.error("凭证流水保存失败");
                    }
                }
                channelOnlineService.updateById(infoTemp);
                try{
                    JSONObject chanelXml = channelOnlineService.sendChannelId(infoTemp);
                    channelIdToCommissionSystemSender.sendAlterDealer(chanelXml.toJSONString());
                }catch (Exception e){
                    log.error("同步佣金系统mq时报");
                }
                try{
                    senderChannelToArchiveImpl.archivePushMQ(infoTemp.getId().toString(), ArchiveConfig.wwsigndealer);
                }catch (Exception e){
                    log.error("同步归档系统mq时报");
                }
            }
            //删除剩余节点数据信息
            for (int i = 0; i < assignList.size(); i++) {
                workTaskAssignService.removeById(assignList.get(i).getId());
            }
            return IResponse.success("提交成功");
        } else {
            return IResponse.fail("提交失败,提交指令异常，请确认！");
        }
    }
}
